package com.cskaoyan.catmall.controller.wx;

import com.cskaoyan.catmall.bean.LoginUserData;
import com.cskaoyan.catmall.config.CustomizedToken;
import com.cskaoyan.catmall.model.pojo.MarketUser;
import com.cskaoyan.catmall.model.vo.*;
import com.cskaoyan.catmall.service.WxAuthService;
import com.cskaoyan.catmall.service.WxHomeIndexService;
import com.cskaoyan.catmall.service.WxUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 创建日期: 2022-01-10-13-56
 * author : LL
 * description: 微信登录
 */
@RequestMapping("wx")
@RestController
public class WxAuthController {
    @Autowired
    WxHomeIndexService wxHomeIndexService;

    @Autowired
    WxAuthService authService;

    @Autowired
    WxUserService userService;



    @GetMapping("home/index")
    public BaseRespVo wxHomeIndex(){
        WxHomeIndexVo homeIndexVo = wxHomeIndexService.getIndex();
        return BaseRespVo.ok(homeIndexVo);
    }


    /**
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @PostMapping("auth/login")
    public BaseRespVo<LoginUserData> login(@RequestBody WxLoginUser user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        String username = user.getUsername();
        String password = user.getPassword();
        CustomizedToken token = new CustomizedToken(username, password, "user");
        try {
            subject.login(token);
            userService.updateUser(request);
            LoginUserVo loginUser = new LoginUserVo();
            loginUser.setToken((String) subject.getSession().getId());
            LoginUserVo.UserInfoDTO userInfoDTO = new LoginUserVo.UserInfoDTO();
            userInfoDTO.setNickName(username);
            userInfoDTO.setAvatarUrl("");
            loginUser.setUserInfo(userInfoDTO);
            return BaseRespVo.ok(loginUser);
        } catch (UnknownAccountException e) {
            return BaseRespVo.fail("用户名错误~");
        } catch (IncorrectCredentialsException e) {
            return BaseRespVo.fail("密码错误~");
        }
    }

    @RequestMapping("user/index")
    public BaseRespVo info() {
        MarketUser principal = (MarketUser) SecurityUtils.getSubject().getPrincipal();
        WxUserIndexVo userIndexVo = userService.getUserIndex(principal);


        return BaseRespVo.ok(userIndexVo);
    }

    @PostMapping("auth/logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }
}